package com.xnyzc.lhy.mis.service.impl.user.pay;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xnyzc.lhy.common.component.payment.AliPay;
import com.xnyzc.lhy.common.component.payment.WeChatPay;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.EOrderType;
import com.xnyzc.lhy.common.penum.order.EOrderNoType;
import com.xnyzc.lhy.common.penum.pay.ERechargeLimit;
import com.xnyzc.lhy.common.penum.wallet.EIsTransaction;
import com.xnyzc.lhy.common.penum.wallet.ERecordType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.mis.entity.user.wallet.OaCWallet;
import com.xnyzc.lhy.mis.entity.user.wallet.OaCWalletRecord;
import com.xnyzc.lhy.mis.entity.util.OrderUtil;
import com.xnyzc.lhy.mis.mapper.user.wallet.OaCWalletMapper;
import com.xnyzc.lhy.mis.mapper.user.wallet.OaCWalletRecordMapper;
import com.xnyzc.lhy.mis.service.user.pay.IOaCUserRechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Description 用户充值
 * @Author zhuyubin
 * @Date 2019/8/14 13:47
 **/
@Service
public class OaCUserRechargeServiceImpl implements IOaCUserRechargeService {

    @Autowired
    private OaCWalletMapper oaCWalletMapper;
    @Autowired
    private OaCWalletRecordMapper oaCWalletRecordMapper;

    /**
     * 用户充值
     * @param userId 用户id
     * @param tag 租户
     * @param type 支付类型
     * @param money 支付金额
     * @return
     */
    @Override
    public Map<String, Object> userRecharge(Long userId, String tag, Integer type, BigDecimal money){
        if (CheckUtil.objIsEmpty(money)){
            throw PangException.create(EErrorCode.notMoney);
        }
        if (money.compareTo(ERechargeLimit.rechargeLimit.getMoney()) == 1){
            throw PangException.create(EErrorCode.notRechargeLimit);
        }
        String pattern = "^(([1-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$";
        Pattern p = Pattern.compile(pattern);
        boolean matches = Pattern.matches(p.pattern(), money.toString());
        if (!matches){
            throw PangException.create(EErrorCode.notMoney);
        }
        Map<String, Object> result = new HashMap<>(16);
        result.put("payType", type);
        result.put("payResultMap", new HashMap<>(16));
        result.put("payResultStr", "");
        String orderNo = OrderUtil.orderNo(EOrderType.CZYE);
        // 微信
        if (type.equals(1)){
            result.put("payType", type);
            result.put("payResultMap", WeChatPay.getWXPayParam(orderNo, EOrderNoType.CZYE.getDesc(), money.toString(), new JSONObject()));
            // 正式环境放开
            this.insertOaCWalletRecord(userId, orderNo, money, tag, ERecordType.weChatTopUp);
            return result;
        }
        // 支付宝
        else if (type.equals(0)){
            result.put("payType", type);
            result.put("payResultStr", AliPay.getAliPayParam(orderNo, EOrderNoType.CZYE.getDesc(), money.toString(), new JSONObject()));
            // 正式环境放开
            this.insertOaCWalletRecord(userId, orderNo, money, tag, ERecordType.alipayTopUp);
            return result;
        }
        // 非法类型
        else {
            throw PangException.create(EErrorCode.unPayType);
        }
    }

    /**
     * 插入钱包记录
     * @param userId 用户id
     * @param orderNo 订单号
     * @param money 金额
     * @param tag 租户
     */
    private void insertOaCWalletRecord(Long userId, String orderNo, BigDecimal money, String tag, ERecordType eRecordType){
        // 钱包
        OaCWallet oaCWallet = oaCWalletMapper.selectOne(
                Wrappers.<OaCWallet>lambdaQuery()
                        .eq(OaCWallet::getUserId, userId)
                        .eq(OaCWallet::getTag, tag)
        );
        if (CheckUtil.objIsEmpty(oaCWallet)){
            throw PangException.create(EErrorCode.unWallet);
        }
        Date date = new Date();
        OaCWalletRecord oaCWalletRecord = new OaCWalletRecord();
        oaCWalletRecord.setRecordId(IDUtil.nextId());
        oaCWalletRecord.setUserId(userId);
        oaCWalletRecord.setOrderNo(orderNo);
        oaCWalletRecord.setActualAmount(money);
        oaCWalletRecord.setIsTransaction(EIsTransaction.payFailed.getValue());
        oaCWalletRecord.setWalletBalance(oaCWallet.getWalletBalance());
        oaCWalletRecord.setPersonalOfficialBalance(oaCWallet.getPersonalOfficialBalance());
        oaCWalletRecord.setDeptOfficialBalance(oaCWallet.getDeptOfficialBalance());
        oaCWalletRecord.setRecordType(eRecordType.getType());
        oaCWalletRecord.setTag(tag);
        oaCWalletRecord.setCreateUser(userId);
        oaCWalletRecord.setCreateTime(date);
        oaCWalletRecord.setUpdateUser(userId);
        oaCWalletRecord.setUpdateTime(date);
        int insert = oaCWalletRecordMapper.insert(oaCWalletRecord);
        if (insert != 1){
            throw PangException.create(EErrorCode.payFailure);
        }
    }
}
